# 使用cookie登录淘宝
import time
from time import sleep

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options

# 打开浏览器
service = Service(r"D:\app\Python38\chromedriver.exe")
chrome_options = Options()
chrome_options.add_experimental_option("detach", True)
# 创建浏览器对象
driver = webdriver.Chrome(options=chrome_options)

"""
需求：使用cookie实现跳过登录
1). 手动登录淘宝，获取cookie
2). 使用获取到的cookie，达到登录目的，然后就可以执行登录之后的操作
"""
# 1. 先访问淘宝页面，确保域名匹配（关键步骤）
driver.get("https://www.taobao.com")
# 等待页面加载
time.sleep(2)

# 2. Cookie字符串
cookie_str = "cookie2=12c6c23f4df37dce7b2d9f63f6cf2d7a; t=c79670c26cbea2ecc64a2bda4a515594; _tb_token_=e7eadb5f76e3e; mtop_partitioned_detect=1; _m_h5_tk=d89329d880cac1f09c4c89cc3071b993_1762264989303; _m_h5_tk_enc=cf44bc91de6de684f09ac5776938c724; thw=xx; cna=RtWQIRHvgz8BASQIiVY4uBrt; arms_uid=62485a75-717e-4a9d-bb51-7be229591e96; xlly_s=1; sca=13b656f3; _samesite_flag_=true; 3PcFlag=1762256775237; wk_cookie2=1b4a556154880b476c0e3da44e034a7f; wk_unb=UUphzOrJ5A26P5%2FtAA%3D%3D; sgcookie=E100jfErHarPne2uytJeBgj2V0DLCTEPid3WH0tn0wwOpTPGKBwrXjd3P5QIQnM0Tto0QgVaqo2n5reLNTRq3gMMl5JjWItg7T5gNsrR%2FKWuVCY%3D; _hvn_lgc_=0; havana_lgc2_0=eyJoaWQiOjIyMDY4MzM0NTU5MzYsInNnIjoiZTY5N2I4NzgwZjAzZDQ5MmVjYmQwOGMyZTE4OTY5NjIiLCJzaXRlIjowLCJ0b2tlbiI6IjFfeGpyaWhBaDBsRVlkbEpXeEF2OUp3In0; unb=2206833455936; csg=d0efe702; lgc=tb049611087; cancelledSubSites=empty; cookie17=UUphzOrJ5A26P5%2FtAA%3D%3D; dnk=tb049611087; skt=d2928fefa8cfd00c; tracknick=tb049611087; _l_g_=Ug%3D%3D; sg=765; _nk_=tb049611087; cookie1=VFCt7aBZnaw431TQ%2FOQImlZSQFlBDc1CCr0qLg%2BtKXA%3D; uc1=cookie16=VT5L2FSpNgq6fDudInPRgavC%2BQ%3D%3D&existShop=false&cookie14=UoYY4dvcRCdYPQ%3D%3D&pas=0&cookie21=UIHiLt3xThN%2B&cookie15=VFC%2FuZ9ayeYq2g%3D%3D; sn=; uc3=id2=UUphzOrJ5A26P5%2FtAA%3D%3D&lg2=UtASsssmOIJ0bQ%3D%3D&nk2=F5RFhBf5tGlAeRY%3D&vt3=F8dD2kv%2F1gI3%2FdUPDwQ%3D; existShop=MTc2MjI1Njc5OA%3D%3D; uc4=nk4=0%40FY4O7bgAgzXjElrpc%2BPcF7XX9Pw%2B%2Bw%3D%3D&id4=0%40U2grF8GBCsksTgpPFUbm9TJZ7SqRZ1sU; _cc_=URm48syIZQ%3D%3D; aui=2206833455936; havana_lgc_exp=1793360803637; sdkSilent=1762285603636; havana_sdkSilent=1762285603636; tfstk=gTGoQMZ_5YyWrEC5EeVWEjEaho9ve7NQCDCLvWEe3orf2gC-8yPn0DL722-SxXq4aJM8vuE3t2iMkhd964g7OS-9XCdoythT6MSULME40WUn6C05g4g7OW7AYdHqPBVRf11U8k80gyzU8WyPaoW4cyBzYDrz3izg5WrEYDy4gyzCYzzzzsr4cyPUYDPeoqrb-WrEYW8mujEhdlmSXj-ICd8GkSAEMz2ub4roy4hVJ86SoofFTjm48lRzm65Eiz0UmKiAspEZCueTcmRAZW04-c4iqi-0TqcSs-lyc6mimAP0lxthKlDEyAMUnURro7quIjeAz9VoL0G3FYbB5qPrcAZ_UKtbobhTKlwc03uxouyiK0KfTuHium2tMiCTgVk0igJh3OJx16a2JjWCd8zbolE8CUmMtseizEYcCIyzlzODoEXCd8zbolLDoOW4UraWi; isg=BLe3XzgKkoeyVBYLHsn8GmUTRqsBfIve8m1ZwAllxAb4uNL6EU9pLlTQnxjmYWNW"

# 3. 拆分Cookie字符串为独立键值对，逐个添加
for cookie_item in cookie_str.split('; '):
    # 分割key和value（处理value中可能包含=的情况）
    if '=' in cookie_item:
        key, value = cookie_item.split('=', 1)
        # 构造单个Cookie字典
        single_cookie = {
            'name': key,
            'value': value,
            'domain': '.taobao.com',  # 淘宝的Cookie通用域名
            'path': '/',
            'httpOnly': False,  # 适配于大部分淘宝Cookie
            'secure': False     # 非HTTPS环境也能生效
        }
        try:
            driver.add_cookie(single_cookie)
            print(f"添加成功Cookie: {key}")
        except Exception as e:
            # 部分Cookie可能因格式限制添加失败，不影响整体使用
            print(f"跳过的Cookie {key}: {str(e)[:50]}")

# 4. 刷新页面使Cookie生效
time.sleep(3)
driver.refresh()

time.sleep(3)
# 5. 退出浏览器
driver.quit()